<?php

/**
 * Offer form.
 *
 * @package    reduceri-cadouri
 * @subpackage form
 * @author     Your name here
 */
class OfferForm extends BaseOfferForm
{
  public function configure()
  {
    unset($this['unique_id'], $this['discount'], $this['created_at']);
    
    $this->widgetSchema['name'] = new sfWidgetFormTextarea();
    $this->widgetSchema['description'] = new sfWidgetFormTextarea();
    $this->widgetSchema['start_time'] = new sfWidgetFormInputText();
    $this->widgetSchema['end_time'] = new sfWidgetFormInputText();
    $this->widgetSchema['remaining_time'] = new sfWidgetFormInputText();
    
    $this->widgetSchema['city_id'] = new sfWidgetFormPropelChoice(array('model' => 'City', 'expanded' =>  true, 'multiple' => true));
    $this->validatorSchema['city_id'] = new sfValidatorPropelChoice(array('model' => 'City', 'multiple' => true));
    $this->validatorSchema['remaining_time'] = new sfValidatorString(array('required' =>  false));
    
    $city_ids = array();
    $cities = $this->getObject()->getOfferCitys();
    foreach($cities as $offer_city)
    {
      $city_ids[] = $offer_city->getCityid();
    }
    $this->setDefault('city_id', $city_ids);
  }
  
  public function save($con = null)
  {
    $offer = parent::updateObject();
    if($this->getValue('remaining_time'))
    {
      $time_parts = explode(":", $this->getValue('remaining_time'));
      $hours = $minutes = $seconds = 0;
      if(isset($time_parts[0]))
      {
        $hours = $time_parts[0];
      }
      if(isset($time_parts[1]))
      {
        $minutes = $time_parts[1];
      }
      if(isset($time_parts[2]))
      {
        $seconds = $time_parts[2];
      }
      
      $offer->setStartTime(date('Y-m-d 00:00:00'));
      $offer->setEndTime(date('Y-m-d H:i:s', time() + $hours * 3600 + $minutes * 60 + $seconds));
    }
    if($offer->getOnsite())
    {
      $offer->save(null, true);
    }
    else
    {
      $offer->save();
    }
    
    
    OfferCityPeer::deleteOfferCities($offer->getId());
    foreach($this->getValue('city_id') as $city_id)
    {
      $offer_city = new OfferCity();
      $offer_city->setOfferId($offer->getId());
      $offer_city->setCityId($city_id);
      $offer_city->save();
    }
    
    return $offer;
  }
}
